package cn.yunbamboos.webfilter;

import cn.yunbamboos.rest.service.logs.LogMetadataThreadLocal;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import org.springframework.context.ApplicationEventPublisher;

import java.io.IOException;

public class GlobalWebFilter implements Filter {

    private final ApplicationEventPublisher applicationEventPublisher;

    public GlobalWebFilter(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            // 发送存储日志事件
            LogMetadataThreadLocal.send(applicationEventPublisher, this);
        }
    }
}
